<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增商品</el-button>
        <el-button type="success" :icon="Edit" @click="handleEditDeliveryFee">修改快递费</el-button>
      </div>
    </template>
    <el-table
        :load="state.loading"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
    >
      <el-table-column
          prop="goodsId"
          label="商品编号"
      >
      </el-table-column>
      <el-table-column
          prop="goodsName"
          label="商品名"
      >
      </el-table-column>
      <el-table-column
          prop="goodsIntro"
          label="商品简介"
      >
      </el-table-column>
      <el-table-column
          label="商品图片"
          width="150px"
      >
        <template #default="scope">
          <img style="width: 100px; height: 100px;" :key="scope.row.goodsId" :src="$filters.prefix(scope.row.goodsCoverImg)" alt="商品主图">
        </template>
      </el-table-column>
      <el-table-column
          prop="stockNum"
          label="商品库存"
      >
      </el-table-column>
      <el-table-column
          prop="sellingPrice"
          label="商品售价"
      >
      </el-table-column>
      <el-table-column
          label="上架状态"
      >
        <template #default="scope">
          <span style="color: green;" v-if="scope.row.goodsSellStatus == 0">销售中</span>
          <span style="color: red;" v-else>已下架</span>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          width="100"
      >
        <template #default="scope">
          <a style="cursor: pointer; margin-right: 10px" @click="handleEdit(scope.row.goodsId)">修改</a>
          <a style="cursor: pointer; margin-right: 10px" v-if="scope.row.goodsSellStatus == 0" @click="handleStatus(scope.row.goodsId, 1)">下架</a>
          <a style="cursor: pointer; margin-right: 10px" v-else @click="handleStatus(scope.row.goodsId, 0)">上架</a>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
    />

    <!-- 快递费配置弹窗 -->
    <el-dialog
        v-model="state.deliveryFeeDialogVisible"
        title="快递费配置"
        width="400px"
    >
      <el-form :model="state.deliveryFeeForm" label-width="100px">
        <el-form-item label="快递费">
          <el-input-number
              v-model="state.deliveryFeeForm.defaultFee"
              :min="0"
              :max="1000"
              :precision="2"
              :step="1"
              controls-position="right"
              style="width: 200px;"
          />
          <div style="color: #666; font-size: 12px; margin-top: 5px;">设置默认快递费用，单位：元</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.deliveryFeeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveDeliveryFee">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance } from 'vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const app = getCurrentInstance()
const { goTop } = app.appContext.config.globalProperties
const router = useRouter()
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  deliveryFeeDialogVisible: false, // 快递费配置弹窗
  deliveryFeeForm: {
    defaultFee: 0
  }
})

onMounted(() => {
  getGoodList()
})

// 获取商品列表
const getGoodList = () => {
  state.loading = true
  axios.get('/goods/list', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
    goTop && goTop()
  })
}

// 打开修改快递费弹窗
const handleEditDeliveryFee = async () => {
  try {
    // 获取当前快递费配置
    const res = await axios.get('/goods/delivery-fee')
    console.log('获取快递费配置响应:', res) // 调试用

    if (res) {
      const configData = res
      if (configData) {
        // 有现有配置
        state.deliveryFeeForm = {
          id: configData.id,
          defaultFee: parseFloat(configData.defaultFee) || 0
        }
        console.log('设置的表单数据:', state.deliveryFeeForm) // 调试用
      } else {
        // 如果没有配置，使用默认值
        state.deliveryFeeForm = {
          defaultFee: 0
        }
      }
    } else {
      // 如果接口返回错误，使用默认值
      state.deliveryFeeForm = {
        defaultFee: 0
      }
    }
    state.deliveryFeeDialogVisible = true
  } catch (error) {
    console.error('获取快递费配置失败:', error)
    // 如果获取失败，使用默认值
    state.deliveryFeeForm = {
      defaultFee: 0
    }
    state.deliveryFeeDialogVisible = true
  }
}

// 保存快递费配置
const handleSaveDeliveryFee = async () => {
  if (state.deliveryFeeForm.defaultFee < 0) {
    ElMessage.error('快递费不能为负数')
    return
  }

  try {
    // 确保传递正确的数据格式
    const submitData = {
      defaultFee: state.deliveryFeeForm.defaultFee
    }

    // 如果有ID，也传递过去
    if (state.deliveryFeeForm.id) {
      submitData.id = state.deliveryFeeForm.id
    }

    console.log('提交的数据:', submitData) // 调试用

    const res = await axios.post('/goods/delivery-fee', submitData)

    console.log('res:', res) // 调试用
    if (res && res.resultCode === 200) {
      ElMessage.success('保存成功')
      state.deliveryFeeDialogVisible = false
    } else {
      ElMessage.error('保存失败：')
    }
  } catch (error) {
    console.error('保存快递费配置失败:', error)
    ElMessage.error('保存失败：' )
  }
}

const handleAdd = () => {
  router.push({ path: '/add' })
}

const handleEdit = (id) => {
  router.push({ path: '/add', query: { id } })
}

const changePage = (val) => {
  state.currentPage = val
  getGoodList()
}

const handleStatus = (id, status) => {
  axios.put(`/goods/status/${status}`, {
    ids: id ? [id] : []
  }).then(() => {
    ElMessage.success('修改成功')
    getGoodList()
  })
}
</script>

<style scoped>
.good-container {
  min-height: 100%;
}
.el-card.is-always-shadow {
  min-height: 100%!important;
}
.header {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
